package networkCode.leetcode;

public class LeetCode7 {

    /**
     * String to integer
     */
    public static void main(String[] args) {
        int temp = myAtoi1("-+1");
        System.out.println(temp);

//        System.out.println("abc123".charAt(3)==47);

    }

    //方法通过，但是无法提交：
    public static int myAtoi(String str) {
        String number = "";
        //正负号存放
        int flag = 1;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '+') {
                continue;
            } else if (str.charAt(i) == '-') {
                number = number + "-";
                continue;
            } else if (str.charAt(i) > 47 && str.charAt(i) < 58) {
                number += str.charAt(i);
            } else if (str.charAt(i) == ' ') {
                continue;
            } else if (64 < str.charAt(i) && str.charAt(i) < 123)
                continue;
            else break;
        }
        if (number == null||number=="" ||number.equals("-")) return 0;
        String temp = str.substring(0, str.indexOf(number.charAt(0)));
        for (int j = 0; j < temp.length(); j++) {
            if(number.charAt(0)=='-'&& temp.charAt(j)=='+'){
                number="0";
            }
            if (64 < temp.charAt(j) && str.charAt(j) < 123) {
                number = "0";
            }
        }

        long resultNumber = Long.parseLong(number);
        if (resultNumber < -2147483648)
            return -2147483648;
        else if (resultNumber > 2147483647)
            return 2147483647;
        return (int) resultNumber;
    }
//    learn from others
    public static int myAtoi1(String str) {
        str = str.trim();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            boolean isDigit = Character.isDigit(c);

            if (i == 0) {
                if (c != '+' && c != '-' && !isDigit) {
                    return 0;
                } else {
                    sb.append(c);
                    continue;
                }
            }

            if (isDigit) {
                sb.append(c);
            } else {
                break;
            }
        }

        String resultAsString = sb.toString();

        if (resultAsString.isEmpty()) {
            return 0;
        }

        char firstCharacter = resultAsString.charAt(0);

        if (resultAsString.length() == 1 && !Character.isDigit(firstCharacter)) {
            return 0;
        }

        try {
            return Integer.parseInt(resultAsString);
        } catch (NumberFormatException e) {
            return firstCharacter == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
    }

}
